import { createHash } from 'crypto';
import { createReadStream } from 'fs';

export const calculateFileHash = async (
  file: Express.Multer.File,
  algorithm: string,
): Promise<string> => {
  return new Promise((resolve, reject) => {
    const hash = createHash(algorithm);

    file.stream.on('data', (data: Buffer) => hash.update(data));
    file.stream.on('end', () => resolve(hash.digest('hex')));
    file.stream.on('error', (err) => reject(err));
  });
};

export const calculateFilePathHash = (path: string, algorithm: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    const hash = createHash(algorithm);
    const stream = createReadStream(path);

    stream.on('data', (data) => hash.update(data));
    stream.on('end', () => resolve(hash.digest('hex')));
    stream.on('error', (err) => reject(err));
  });
};
